package resources

import (
	"context"
	"errors"
	"gitee.com/Luna-CY/hui-hui/internal/logger"
	"gitee.com/Luna-CY/hui-hui/internal/util/archive"
	"os"
	"path/filepath"
	"strings"
)

// Decompress 解压
func (cls *Resources) Decompress(paths []string) error {
	var path, err = cls.normal(paths)
	if nil != err {
		return err
	}

	path = filepath.Join(cls.path, path)
	stat, err := os.Stat(path)
	if nil != err && !os.IsNotExist(err) {
		return err
	}

	if os.IsNotExist(err) {
		return errors.New("文件不存在")
	}

	if stat.IsDir() {
		return errors.New("不是文件")
	}

	var ext = filepath.Ext(path)
	if ".gz" != ext && ".xz" != ext && ".zip" != ext {
		return errors.New("未支持的压缩类型")
	}

	cls.sm.Lock()
	cls.state[path] = EntryStateDecompressing
	cls.sm.Unlock()

	defer func() {
		cls.sm.Lock()
		defer cls.sm.Unlock()

		delete(cls.state, path)
	}()

	f, err := os.Open(path)
	if nil != err {
		return err
	}

	defer func() {
		if err := f.Close(); nil != err {
			logger.GetLogger().Sugar().Errorf("关闭文件失败: %s, %v", path, err)
		}
	}()

	switch ext {
	case ".gz":
		if strings.HasSuffix(path, ".tar.gz") {
			return archive.DecompressTarGzipFile(context.Background(), f, stat.Size(), filepath.Dir(path), nil)
		}

		return archive.DecompressGzipFile(context.Background(), f, stat.Size(), filepath.Dir(path), nil)
	case ".xz":
		if strings.HasSuffix(path, ".tar.xz") {
			return archive.DecompressTarXzFile(context.Background(), f, stat.Size(), filepath.Dir(path), nil)
		}

		return archive.DecompressXzFile(context.Background(), f, stat.Size(), filepath.Dir(path), nil)
	case ".zip":
		return archive.DecompressZipFile(context.Background(), f, stat.Size(), filepath.Dir(path), nil)
	}

	return nil
}
